package com.softer.chengxin.dicinfo.service.impl;

import com.softer.chengxin.common.domin.CommonResult;
import com.softer.chengxin.common.domin.JsonResult;
import com.softer.chengxin.common.domin.ManagerPageResult;
import com.softer.chengxin.common.domin.Page;
import com.softer.chengxin.common.enums.ResultEnum;
import com.softer.chengxin.dicinfo.dao.DicInfoDao;
import com.softer.chengxin.dicinfo.entity.DicInfo;
import com.softer.chengxin.dicinfo.service.DicInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Gong Zhiyang
 * @date 2018/10/13
 */
@Service
public class DicInfoServiceImpl implements DicInfoService {
    @Autowired
    private DicInfoDao dicInfoDao;

    @Override
    public ManagerPageResult getData(Page page, DicInfo dicInfo) {
        ManagerPageResult mr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        int count = dicInfoDao.getCount(dicInfo.getTypeCode());
        List<DicInfo> list = new ArrayList<>();
        if(count > 0){
            page.setQueryBean(dicInfo);
            list = dicInfoDao.getList(page);
        }
        jr.setDs(list);
        mr.setCount(count);
        mr.setJson(jr);
        return mr;
    }

    @Override
    public CommonResult add(DicInfo dicInfo){
        String init = "001";
        String code = dicInfo.getTypeCode()+init;
        //查询类型code对应字典表中最大的code
        String maxCode = dicInfoDao.getMaxCode(dicInfo.getTypeCode());
        if(StringUtils.isNotBlank(maxCode) && Integer.parseInt(maxCode)>=Integer.parseInt(code)){
            code = String.valueOf(Integer.parseInt(maxCode)+1);
        }
        dicInfo.setCode(code);
        int i = dicInfoDao.insert(dicInfo);
        if(i == 0){
            return new CommonResult(ResultEnum.FAIL.getCode(), "添加失败，请稍后重试！");
        }
        return new CommonResult(ResultEnum.SUCCESS.getCode(), "添加成功！");
    }

    @Override
    public CommonResult update(DicInfo dicInfo) {
        int i = dicInfoDao.update(dicInfo);
        if(i == 0){
            return new CommonResult(ResultEnum.FAIL.getCode(), "修改失败，请稍后重试！");
        }
        return new CommonResult(ResultEnum.SUCCESS.getCode(), "修改成功！");
    }

    @Override
    public CommonResult delete(String id) {
        int i = dicInfoDao.delete(id);
        if(i == 0){
            return new CommonResult(ResultEnum.FAIL.getCode(), "删除失败，请稍后重试！");
        }
        return new CommonResult(ResultEnum.SUCCESS.getCode(), "删除成功！");
    }

    @Override
    public DicInfo getDicInfoById(String id) {
        return dicInfoDao.getDicInfoById(id);
    }
    /**
     * 根据字典类型查询字典信息列表
     * @param typeCode
     * @return
     */
    @Override
    public List<DicInfo> getDicInfoByTypeCode(String typeCode){
        return dicInfoDao.getDicInfoByTypeCode(typeCode);
    }
}
